import { Button, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiDictTree } from "~/api";
import Title from "~/components/ui/title";
import { useDictReload } from "~/contexts/dict";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IDict } from "~/types/common";
import DictModal from "./dict-modal";

export default function Dict() {
  const tableHeight = useTableHeight(223);
  const [dataList, setDataList] = useState<IDict[]>([]);
  const [editDict, setEditDict] = useState<IDict | null>(null);
  const [addParentId, setAddParentId] = useState<number>(0);
  const [modalVisible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const reloadDict = useDictReload();

  const _handler = {
    onCancel: () => {
      setEditDict(null);
      setModalVisible(false);
    },
    onOk: () => {
      setModalVisible(false);
      _fetch.init();
      reloadDict();
    },
    addDict: async (record?: IDict) => {
      setAddParentId(record?.id || 0);
      setEditDict(null);
      setModalVisible(true);
    },
    editDict: async (record: IDict) => {
      setAddParentId(record.parentId);
      setEditDict(record);
      setModalVisible(true);
    },
  };

  const _ui: {
    tableColumns: ColumnsType<IDict>;
  } = {
    tableColumns: [
      {
        title: "名称",
        dataIndex: "label",
        key: "label",
        fixed: "left",
        width: 300,
      },
      {
        title: "唯一CODE",
        dataIndex: "code",
        key: "code",
        width: 360,
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        minWidth: 200,
      },
      {
        title: "操作",
        key: "action",
        fixed: "right",
        width: 100,
        render: (_, record) => {
          return (
            <div className="flex items-center justify-end gap-2">
              {record.parentId === 0 && (
                <Button
                  type="link"
                  size="small"
                  onClick={() => _handler.addDict(record)}
                >
                  新增子类型
                </Button>
              )}
              <Button
                type="link"
                size="small"
                onClick={() => _handler.editDict(record)}
              >
                编辑
              </Button>
            </div>
          );
        },
      },
    ],
  };

  const _fetch = {
    init: async () => {
      setLoading(true);
      const resp = await apiDictTree();
      setDataList(resp);
      setLoading(false);
    },
  };

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <>
      <Title
        title="字典配置"
        buttonGroups={[
          <Button
            type="primary"
            onClick={() => {
              _handler.addDict();
            }}
          >
            <PlusIcon size={18} />
            添加字典
          </Button>,
        ]}
      />
      <div className="h-full w-full">
        <Table
          loading={loading}
          scroll={{
            y: tableHeight,
            x: "max-content",
          }}
          rowKey={(item) => item.code}
          columns={_ui.tableColumns}
          dataSource={dataList}
          pagination={false}
        />
      </div>

      <DictModal
        defaultParentId={addParentId}
        dict={editDict}
        visible={modalVisible}
        onCancel={_handler.onCancel}
        onOk={_handler.onOk}
      />
    </>
  );
}
